using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MapGenerat : MonoBehaviour
{
   private int mapWidth=5;
   private int mapHeight=5;

   private float tileSize=1.2f;

   public GameObject WallPrefab;
   public GameObject groundPrefab;
   public GameObject exitPrefab;
   public GameObject PlayerPrefab;

   private int[] mapData={
        1,1,1,1,1,
        1,0,0,0,1,
        1,0,1,0,1,
        1,0,0,0,1,
        1,1,1,0,2
   };

   private GameObject playerInstancs;
   private Vector2Int playerGridPos;
    void Start()
    {
        GenerateMap();
        SpawnPlayer();
    }

   void GenerateMap(){
        for(int y=0;y<mapHeight;y++){
            for(int x=0;x<mapWidth;x++){
                Vector3 spawnPos=new Vector3(
                    x*tileSize,
                    0,
                    y*tileSize
                );
                int index=GetIndexFormGrid(x,y);

                switch(mapData[index]){
                    case 0:
                        Instantiate(groundPrefab,spawnPos,Quaternion.identity,transform);
                        break;
                        case 1:
                        Instantiate(WallPrefab,spawnPos,Quaternion.identity,transform);
                        break;
                        case 2:
                        Instantiate(exitPrefab,spawnPos,Quaternion.identity,transform);
                        break;
                }

            }
        }
   }

   void SpawnPlayer(){
        playerGridPos=new Vector2Int(1,1);

        Vector3 playerpos=GridToWorldPosition(playerGridPos);

        playerInstancs =Instantiate(
            PlayerPrefab,
            playerpos,
            Quaternion.identity
        );
   }

   public bool IsMoveValid(Vector2Int targetPos){
        if(targetPos.x<0||targetPos.x>=mapWidth) return false;
        if(targetPos.y<0||targetPos.y>=mapHeight) return false;
        int index =GetIndexFormGrid(targetPos.x,targetPos.y);
        return mapData[index]!=1;        
   }

   public void MovePlayer(Vector2Int newPos){
    playerGridPos=newPos;
    playerInstancs.transform.position=GridToWorldPosition(newPos);
    int index=GetIndexFormGrid(newPos.x,newPos.y);
    if(mapData[index]==2){
        Debug.Log("胜利！达到出口");
    }

   }

   public Vector2Int GetPlayerGridPosition(){
        return playerGridPos;
   }

   Vector3 GridToWorldPosition(Vector2Int gridPos){
        return new Vector3(
            gridPos.x*tileSize,
            0.5f,
            gridPos.y*tileSize
        );
   }


   private int GetIndexFormGrid(int x,int y){
        return y*mapWidth+x;
   }
}
